<template>
  <div
    style="
      border: 1px solid #ccc;
      margin-top: 10px;
      z-index: 9;
      position: relative;
      width: 100%;
    "
  >
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      :defaultConfig="editorConfig"
      :mode="mode"
      v-model="valueHtml"
      style="height: 400px; overflow-y: hidden"
      @onCreated="handleCreated"
      @onChange="handleChange"
      @onDestroyed="handleDestroyed"
      @onFocus="handleFocus"
      @onBlur="handleBlur"
      @customAlert="customAlert"
      @customPaste="customPaste"
    />
  </div>
</template>

<script lang="ts">
// api文档：https://www.wangeditor.com/v5/menu-config.html#%E9%93%BE%E6%8E%A5
import {
  defineComponent,
  onBeforeUnmount,
  getCurrentInstance,
  onMounted,
  shallowRef,
  ref,
  reactive,
  toRefs,
} from "vue";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { constants, Session } from "@/store/Session";
import request from "@/http/request";
export default defineComponent({
  name: "contextEditor",
  components: { Editor, Toolbar },
  props: {
    urlToken: {
      type: String,
      default: "",
    },
  },
  emits: ["funSuccess"],
  setup(props) {
    const { proxy }: any = getCurrentInstance();
    interface dataProps {
      editorRef: any;
      mode: any;
      valueHtml: any;
      toolbarConfig: any;
      editorConfig: any;
      handleCreated: (editor: any) => void;
      handleChange: (editor: any) => void;
      handleDestroyed: (editor: any) => void;
      handleFocus: (editor: any) => void;
      handleBlur: (editor: any) => void;
      customAlert: (info: any, type: any) => void;
      customPaste: (editor: any, event: any, callback: any) => void;
      insertText: () => void;
      printHtml: () => void;
      disable: () => void;
    }
    const dataRef: dataProps = reactive({
      editorRef: shallowRef(), // 编辑器实例，必须用 shallowRef，重要！
      mode: "default", // default,simple
      valueHtml: "", //内容 HTML
      toolbarConfig: {},
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {
          // 上传图片的配置
          uploadImage: {
            server: "/api-file/files-anon",
            fieldName: "wangeditor-uploaded-image",
            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 5 * 1024 * 1024, // 1M
            // 最多可上传几个文件，默认为 100
            //maxNumberOfFiles: 10,
            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ["image/*"],
            meta: {
              token: "",
            },
            // 将 meta 拼接到 url 参数中，默认 false
            metaWithUrl: true,
            headers: {
              "Cache-Control": "no-cache",
              "X-Requested-With": "XMLHttpRequest",
              "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
            },
            // 跨域是否传递 cookie ，默认为 false
            withCredentials: false,
            // 超时时间，默认为 10 秒
            timeout: 10 * 1000, // 5 秒
            async customUpload(file: File, insertFn: any) {
              // file 即选中的文件
              // 自己实现上传，并得到图片 url alt href
              // 最后插入图片
              const formData = new FormData();
              formData.append("file", file);
              const res: any = await request.files.uploadFile(formData);
              insertFn(res.url + "?" + props.urlToken);
            },
          },
          // 上传视频的配置
          uploadVideo: {
            server: "/api-file/files-anon",
            fieldName: "wangeditor-uploaded-video",
            // 单个文件的最大体积限制，默认为 10M
            maxFileSize: 50 * 1024 * 1024, // 5M
            // 最多可上传几个文件，默认为 5
            maxNumberOfFiles: 5,
            // 选择文件时的类型限制，默认为 ['video/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ["video/*"],
            meta: {
              token: "",
            },
            // 将 meta 拼接到 url 参数中，默认 false
            metaWithUrl: true,
            headers: {
              "Cache-Control": "no-cache",
              "X-Requested-With": "XMLHttpRequest",
              "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
            },
            // 跨域是否传递 cookie ，默认为 false
            withCredentials: false,
            // 超时时间，默认为 10 秒
            timeout: 30 * 1000, // 5 秒
            // 自定义上传
            async customUpload(file: File, insertFn: any) {
              // file 即选中的文件
              // 自己实现上传，并得到视频 url
              // 最后插入视频
              const formData = new FormData();
              formData.append("file", file);
              const res: any = await request.files.uploadFile(formData);
              insertFn(res.url + "?" + props.urlToken);
            },
          },
          // 代码语言高亮
          codeSelectLang: {
            // codeLangs: [
            //   { text: 'CSS', value: 'css' },
            //   { text: 'HTML', value: 'html' },
            //   { text: 'XML', value: 'xml' },
            //   // 其他
            // ]
          },
        },
      },
      handleCreated: (editor: any) => {
        dataRef.editorRef = editor; // 记录 editor 实例，重要！
      },
      handleChange: (editor: any) => {
        // console.log('change:', editor.getHtml());
        proxy.$emit("funSuccess", editor.getHtml());
      },
      handleDestroyed: (editor: any) => {
        console.log("destroyed", editor); //销毁
      },
      handleFocus: (editor: any) => {
        console.log("focus", editor);
      },
      handleBlur: (editor: any) => {
        console.log("blur", editor);
      },
      customAlert: (info: any, type: any) => {
        alert(`【自定义提示】${type} - ${info}`);
      },
      customPaste: (editor: any, event: any, callback: any) => {
        console.log("ClipboardEvent 粘贴事件对象", event);
        // 自定义插入内容
        //editor.insertText('xxx')
        // 返回值（注意，vue 事件的返回值，不能用 return）
        //callback(false) // 返回 false ，阻止默认粘贴行为
        callback(true); // 返回 true ，继续默认的粘贴行为
      },
      insertText: () => {
        const editor = dataRef.editorRef;
        if (editor == null) return;
        editor.insertText("hello world");
      },
      printHtml: () => {
        const editor = dataRef.editorRef;
        if (editor == null) return;
        console.log(editor.getHtml());
      },
      disable: () => {
        const editor = dataRef.editorRef;
        if (editor == null) return;
        editor.disable();
      },
    });

    onMounted(() => {
      setTimeout(() => {
        //valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
      }, 1500);
    });
    // 组件销毁时，也及时销毁编辑器，重要！
    onBeforeUnmount(() => {
      const editor = dataRef.editorRef;
      if (editor == null) return;
      editor.destroy();
    });

    return {
      ...toRefs(dataRef),
    };
  },
});
</script>
<style>
#top-container {
  border-bottom: 1px solid #e8e8e8;
  padding-left: 30px;
}

#editor-toolbar {
  width: 1350px;
  background-color: #fcfcfc;
  margin: 0 auto;
}

#content {
  height: calc(100% - 40px);
  background-color: rgb(245, 245, 245);
  overflow-y: auto;
  position: relative;
}

#editor-container {
  width: 850px;
  margin: 30px auto 150px auto;
  background-color: #fff;
  padding: 20px 50px 50px 50px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 10px rgb(0 0 0 / 12%);
}

#title-container {
  padding: 20px 0;
  border-bottom: 1px solid #e8e8e8;
}

#title-container input {
  font-size: 30px;
  border: 0;
  outline: none;
  width: 100%;
  line-height: 1;
}

#editor-text-area {
  min-height: 900px;
  margin-top: 20px;
}
</style>
